type JSDynamicObject = any;
"use strict";
const util : any = require ('util');
function merge (vals : any [] [], operator : string, chain : any) : any {
    let conds : any [] = [];
    let data : any [] = [];
    vals.forEach (function (val : any) : void {
        where (val, function (vals : any, txt : any) : void {
            data.push.apply (data, vals);
            conds.push (txt);
        });
    });
    return chain (data, conds.length == 1 ? conds [0] : '(' + conds.join (operator) + ')');
}
function escape (value : string) : any {
    return util.format ('"%s"', value);
}
function cond (k : string, v : any, chain : any) : any {
    k = escape (k);
    let type : string = typeof v;
    if (Array.isArray (v) && v.length == 0) return chain ([], "FALSE");
    if (type == "object") return chain ([], `${k} IS${v === null ? '' : ' NOT'} NULL`);
    if (type == "boolean") return chain ([], util.format (v ? '%s' : 'NOT(%s)', k));
    return chain ([v], util.format ('%s=?:', k));
}
function where (vals : any, chain : any) : any {
    return chain ([], vals);
}
const mask : RegExp = new RegExp (`(-)?(#)?(?:"([^"]+)"|'([^']+)'|([^\\s,]+))|(\\s*,\\s*)`, 'g');
function explode_search_blob (qs : any) : any [] {
    qs = qs.trim ();
    let out : any [] = [];
    let tmp ! : string [] | null;
    while (tmp = mask.exec (qs)) out.push (tmp);
    return out;
}
function res (main_field : any, qs : any) : any {
    let out : any [] = explode_search_blob (qs);
    let parts : any [] [] = [[]];
    let part : number = 0;
    out.forEach (function (arg : any []) : any [] {
        if (arg [6]) return parts [++ part] = [];
        let value : any = arg [3] || arg [4] || arg [5];
        parts [part].push ({
            [main_field] : value
        });
    })
    let results ! : JSDynamicObject;
    merge (parts, ' OR ', function (data : any, txt : any) : void {
        results = {
            data,
            txt
        };
    });
}
;
